/**
 * Copyright 2011 Micro_SNS Group. All Right reserved.
 */
package com.team.sns.services.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.team.sns.entities.Actor;
import com.team.sns.entities.Permissions;
import com.team.sns.entities.User;
import com.team.sns.persistence.impl.JPAProvider;
import com.team.sns.services.UserService;
import com.team.sns.utils.WebUtils;

/**
 * @author seven zhao
 * @version 1.0
 * 功能说明：
 *
 */
@Service @Transactional
public class UserServiceBean extends JPAProvider<User> implements UserService{
	
	//全局变量
	public static final Map<Integer,List<String>> PERMISSIONMAP = new HashMap<Integer,List<String>>();
	
	/**
	 * 重写save方法，将密码使用md5进行加密
	 */
	@Override
	public void save(User obj) {
		obj.setPassword(WebUtils.getMD5String(obj.getPassword()));
		super.save(obj);
	}
	
	public User login(User user) {
		String hql = "username=?1 AND password =?2";
		Object[] o = new Object[2];
		o[0] = user.getUsername();
		o[1] = user.getPassword();
		List<User> lst = this.getResultList(1, 1, hql, o);
		if(lst.size() == 0) {
			return null;
		}
		return lst.get(0);
	}
	
	
	/**
	 * 获取用户的权限列表
	 * @param user
	 */
	public void getUserPermissions(User user){
		List<String> lst = new ArrayList<String>();
		
		if(user != null) {
			List<Actor> actors = user.getActors();
			for(Actor a : actors) {
				List<Permissions> perlst = a.getPermissions();
				
				for(Permissions per : perlst) {
					lst.add(per.getAction());
				}
			}
		}
		PERMISSIONMAP.put(user.getId(), lst);
	}

	public boolean chkUsername(String username) {
		String sql = "select count(o) from User o where o.username = ?1";
		long result = (Long)em.createQuery(sql).setParameter(1, username)
		  			       	  .getSingleResult();
		return result>0;
	}

}